<?php

namespace app\common\model;

use think\Exception;
use think\Model;

/**
 * 会员积分日志模型
 */
class ScoreLog extends Model
{

    // 表名
    protected $name = 'user_score_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性

    protected $append = [
        'createtime_text',
    ];

    public const STATUS_XF = 100; //消费兑换
    public const STATUS_GOODS = 200; //商品兑换
    public const STATUS_SIGN = 300; //签到
    public const STATUS_GOODS_CANCEL = 400; //撤销订单
    public const STATUS_XF_CANCEL = 500; //消费撤回


    public const STATUS_ARRAY =  [
        self::STATUS_XF => 'Consumption',
        self::STATUS_GOODS => 'Goods',
        self::STATUS_SIGN => 'Sign',
        self::STATUS_GOODS_CANCEL => 'Goods cancel',
        self::STATUS_XF_CANCEL => 'Consumption cancel',
    ];

    public const NOT_CANCELED = 100;
    public const CANCELED = 200;

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['createtime'] ?? "");
        return is_numeric($value) ? date("d F Y H:i:s", $value) : $value;
    }

    public function user()
    {
        return $this->belongsTo(\app\admin\model\User::class,'user_id','id',[],'LEFT')
            ->setEagerlyType(0);
    }


    public function staff()
    {
        return $this->belongsTo(\app\admin\model\User::class,'staff_id','id',[],'LEFT')
            ->setEagerlyType(0);
    }


    /**
     * Notes: 积分取消兑换
     * User: chenLei
     * Date: 9/17/25
     * @param $logId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function cancelScore($logId,$staff_id)
    {
        $log = ScoreLog::where('id', $logId)->where('status', ScoreLog::STATUS_XF)->find();
        if (empty($log)) {
            $this->error = 'Log does not exist';
            return false;
        }

        if ($log['cancel'] == self::CANCELED) {
            $this->error = 'Log has been canceled';
            return false;
        }


        $this->startTrans();
        try {
            $log->cancel = self::CANCELED;
            $log->cancel_time = time();
            $log->save();

            $user = User::where('id', $log['user_id'])->find();

            $before = $user['score'];
            $user->score = $user['score'] - $log['score'];
            $user->save();

            $end_score = $user->score;
            ScoreLog::create([
                'user_id' => $log['user_id'],
                'score' => $log['score'],
                'before' => $before,
                'after' => $end_score,
                'type' => 2,
                'memo' => 'Score cancel',
                'status' => ScoreLog::STATUS_XF_CANCEL,
                'log_id' => $logId,
                'staff_id' => $staff_id ?? 0
            ]);


            $this->commit();
        } catch (Exception $exception) {
            $this->rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;
    }
}
